import { onMounted, provide, ref, watch,computed } from 'vue';

// CC-- 导入pinia的两个方法
import { storeToRefs } from "pinia";
import {CStore} from '../../stores/counter'

// CC-- 解构出pinia中存储的数据
const $store = CStore()
const {piniaCities} = storeToRefs($store)


export const searchCityData = ()=>{

    // 指示页面元素的显隐
    let isShow = ref('cityList')

    // 与输入框进行双向绑定
    let inputValue = ref('')

    // 存储搜索到的数据
    let sortData = ref([])

    // 监听输入框中内容的变化
    watch(inputValue,(data)=>{
        if(data == false) {
            sortData.value = []
            return
        }
        let timer = null
        // 防抖
       /*  if (timer) clearTimeout(timer);
        timer = setTimeout(()=>{                
            sortCode(data)
        }, 5) */
   
        sortCode(data)
    })

    function sortCode(data) {
        for(let key in piniaCities.value) {
         
            if(data == key) {
           
             for(let obj of piniaCities.value[key]) {
                 sortData.value.push(obj.name)
             }
        
            }else {
          
             for(let obj of piniaCities.value[key]) {
                 let querySpell = obj.spell.indexOf(data)
                 let queryName = obj.name.indexOf(data)
                 if(querySpell != -1 || queryName != -1) {
                     sortData.value.push(obj.name)
                 }
             }
            }
            
 
            if(sortData.value.length > 0) {
             isShow.value = 'searchSuccess'
            }else {
             isShow.value = data
            }
 
 
         }
    }



    function exit () {
        isShow.value = 'cityList'
    }

    return {
        exit,inputValue,isShow,sortData
    }
}